<template>
    <div class="form-floating position-relative mb-2">
        <input
            v-bind="$attrs"
            :id="id || `floating${label}`"
            :value="modelValue"
            :type="showPassword ? 'text' : type"
            :placeholder="label"
            @input="$emit('update:modelValue', $event.target.value)"
            @focus="isFocused = true"
            @blur="isFocused = false"
            :class="['form-control pe-10', $attrs.class]"
        />
        <label :for="id || `floating${label}`">
            {{ label }}
        </label>

        <button
            v-if="modelValue && type !== 'password'"
            type="button"
            class="clear-btn"
            @click="$emit('update:modelValue', '')"
            aria-label="Clear input"
        >
            <i class="bi bi-x-lg"></i>
        </button>

        <button
            v-if="modelValue && type === 'password'"
            type="button"
            class="toggle-password-btn"
            @click="showPassword = !showPassword"
            :aria-label="showPassword ? 'Hide password' : 'Show password'"
        >
            <i :class="showPassword ? 'bi bi-eye-slash' : 'bi bi-eye'"></i>
        </button>
    </div>
</template>

<script setup>
import { ref } from 'vue';

defineProps({
    modelValue: String,
    label: String,
    type: {
        type: String,
        default: 'text'
    },
    id: String
});

defineEmits(['update:modelValue']);

const isFocused = ref(false);
const showPassword = ref(false);
</script>

<style scoped>
.clear-btn,
.toggle-password-btn {
    position: absolute;
    top: 50%;
    right: 0.75rem;
    transform: translateY(-50%);
    border: none;
    background: transparent;
    padding: 0;
    margin: 0;
    cursor: pointer;
    color: #aaa;
    font-size: 1rem;
}

.clear-btn:hover,
.toggle-password-btn:hover {
    color: #333;
}

:root[data-bs-theme='dark'] .clear-btn,
:root[data-bs-theme='dark'] .toggle-password-btn {
    color: #666;
}

:root[data-bs-theme='dark'] .clear-btn:hover,
:root[data-bs-theme='dark'] .toggle-password-btn:hover {
    color: #fff;
}
</style>
